package com.htl.exampro.question.job;

import com.htl.exampro.question.pojo.domain.AnswerDO;
import com.htl.exampro.question.service.CheckAnswerService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 校对答案定时任务
 */
@Component
@Slf4j
public class CheckAnswerJob {
    private final static Long TIMEOUT = 50 * 60 * 100L;
    @Resource
    CheckAnswerService checkAnswerService;

    @XxlJob("CheckAnswerJobHandler")
    void CheckAnswerJobHandler() {
        String message = "";
        try {
            String jobParam = Objects.requireNonNull(XxlJobHelper.getJobParam(), "任务参数不能为空！").trim();
            log.info("CheckAnswerJobHandler, 任务参数：{}, 执行时间:{}", jobParam, LocalDateTime.now());
            message = "CheckAnswerJobHandler,任务参数：" + jobParam + ", 执行时间:" + LocalDateTime.now();
            long timeout = System.currentTimeMillis() + TIMEOUT;
            while (true) {
                long startTime = System.currentTimeMillis();
                if (System.currentTimeMillis() > timeout) {
                    break;
                }
                List<AnswerDO> answerDOS = checkAnswerService.queryAnswer(jobParam);
                if (answerDOS == null || answerDOS.isEmpty()) break;
                checkAnswerService.checkAnswer(answerDOS);
                long l = (System.currentTimeMillis() - startTime) / 1000;
                log.info("CheckAnswerJobHandler,处理{}条数据耗时{}秒", answerDOS.size(), l);
            }

            XxlJobHelper.handleSuccess(message);
        } catch (Exception e) {
            log.error("CheckAnswerJobHandler", e);
            XxlJobHelper.handleFail("系统异常：" + e.getMessage() + " " + message);
        }
    }
}
